package com.nuanshui.heatedloan.msgcenter.processor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.FlagOperationFactory;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.middleware.msgcenter.bean.MsgBody;
import com.nuanshui.heatedloan.msgcenter.apppush.AppPushFacade;
import com.nuanshui.heatedloan.msgcenter.facade.AppPushMsgService;
import com.nuanshui.heatedloan.msgcenter.facade.MessageService;
import com.nuanshui.heatedloan.msgcenter.facade.MsgRedDotStatusService;
import com.nuanshui.heatedloan.msgcenter.facade.SystemMsgService;
import com.nuanshui.heatedloan.msgcenter.form.AppPushMsgForm;
import com.nuanshui.heatedloan.msgcenter.form.MessageInfoForm;
import com.nuanshui.heatedloan.msgcenter.integration.AppPushMsgBody;
import com.nuanshui.heatedloan.msgcenter.model.*;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 推送消息的处理器
 * @ClassName: PushMsgProcessor 
 * @author guohao
 * @date 2016年3月11日 下午2:19:03 
 *
 */
@Component
public class AppPushMsgProcessor implements MsgProcessor {
	Logger log = LoggerFactory.getLogger(AppPushMsgProcessor.class);

	@Autowired
	private MessageService messageService;

	@Autowired
	private SystemMsgService systemMsgService;

	@Autowired
	private AppPushFacade appPushFacade;

	//是否开启测试环境 1 开启 0关闭
	@Value("${msgcenter.push.testenv}")
	private Integer testenv;

	//在这里，封装一些app推送需要的数据。
	public void execute(MsgBody msgBody) {

		AppPushMsgBody appPushMsgBody=(AppPushMsgBody)msgBody;
		//如果 接受者为空则不再做处理
     	List<String> userIds = appPushMsgBody.getDstUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            log.error("dst userId is empty");
            return;
        }



        if(testenv==1)
		{
			if(appPushMsgBody.getEnv()==null)
			{
				appPushMsgBody.setEnv(MsgBody.ENV_TEST);
			}
		}
		else if(testenv==0)
		{
			if(appPushMsgBody.getEnv()==null)
			{
				appPushMsgBody.setEnv(MsgBody.ENV_RELEASE);
			}
		}

        MessageInfoForm messageInfo = new MessageInfoForm();
        messageInfo.setMessageType(appPushMsgBody.getMessageType());
		messageInfo.setMessageTypeName(appPushMsgBody.getMsgTypeName());
        messageInfo.setBizId(appPushMsgBody.getBizId());
        messageInfo.setUserId(appPushMsgBody.getBizUserId());
        messageInfo.setPushParams(appPushMsgBody.getPushParams());
        if (MsgOperationType.ADD.equals(appPushMsgBody.getMsgOperationType())) {//发布一个消息
            messageService.addMsgInfo(messageInfo, userIds);

			saveSystemMsg(appPushMsgBody);

        	AppPushMessage appPushMessage = new AppPushMessage();
			appPushMessage.setMsgBody(appPushMsgBody);
            appPushFacade.push(appPushMessage);  //进行推送
        }
        else if(MsgOperationType.DELETE.equals(appPushMsgBody.getMsgOperationType())){//删除一个消息
            messageService.delMsgInfo(messageInfo);
        }
	}

	private void saveSystemMsg(AppPushMsgBody msgBody)
	{
		if(!FlagOperationFactory.getResultOp().containFlag(msgBody.getFlag(), AppPushMsgBody.FLAG_PERSISTENCE))
			return;

		if(msgBody.getPushTime() == null) {
			msgBody.setPushTime(new Date());
		}

		if(msgBody.getMessageType()==null) return;

		MsgBizType bizType=MsgBizType.getBizType(msgBody.getMessageType());

		if(bizType!=null)
		{
			String title=msgBody.getMsgTitle();
			String content=msgBody.getMsgContent();
			if(SysStringUtils.isNotEmpty(msgBody.getBizId()))
			{
				AppPushMsgForm msg= appPushMsgService.loadCacheMsg(msgBody.getBizId());
				if(msg!=null)
				{
					if(SysStringUtils.isNotEmpty(msg.getSystemMsgTitle()))
					{
						title=msg.getSystemMsgTitle();
					}
					if(SysStringUtils.isNotEmpty(msg.getSystemContent()))
					{
						content=msg.getSystemContent();
					}
				}
			}

			SystemMsg systemMsg = new SystemMsg();
			systemMsg.setTitle(title);
			systemMsg.setContent(content);
			systemMsg.setDirectUrl(msgBody.getDirectUrl());
			systemMsg.setCreatedAt(msgBody.getPushTime());
			systemMsg.setImageId(msgBody.getImageId());
			systemMsg.setBizType(msgBody.getMessageType());
			systemMsg.setUserId(msgBody.getDstUserId());
			systemMsgService.insert(systemMsg);
			//设置系统消息红点
			List<String> userIdsArray = msgBody.getDstUserIds();
			msgRedDotStatusService.mark(userIdsArray, bizType, MsgOperationType.ADD);
		}
	}

	@Autowired
	private MsgRedDotStatusService msgRedDotStatusService;

	@Autowired
	private AppPushMsgService appPushMsgService;

	@Reference(url= GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserQueryService userQueryService;

}
